//
//  CabinetAppDelegate.m
//  Cabinet
//
//  Created by Florent Montsegur on 12/03/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CabinetAppDelegate.h"
#import "Person.h"
#import "SearchPatient.h"
#import "SearchDiagnostic.h"
#import "MajTextFieldFormatter.h"
#import "Waiting.h"
#import "CabinetDefines.h"
#import "Diagnostic.h"
#import "EtatConsultationController.h"
#import "VaccinationController.h"
#import "Rang.h"
#import "Vaccin.h"
#import "Vaccination.h"
#import "GestionPersonController.h"


@implementation CabinetAppDelegate

@synthesize window;
@synthesize mConsultations;
@synthesize mImpayes;

@synthesize mConsDay;
@synthesize mConsNum;
@synthesize mConsDate;
@synthesize mConsNom;
@synthesize mConsPrenom;
@synthesize mConsDiag;
@synthesize mConsRef;
@synthesize mConsTraitement;
@synthesize mConsMoyenPaiement;
@synthesize mConsActe;
@synthesize mConsPaye;
@synthesize mConsSomme;
@synthesize mTotalImpayes;

@synthesize mRenouvellement;
@synthesize mEnregistrer;
@synthesize mNouvelActe;
@synthesize mMenuNouvelActe;

@synthesize mConsInfos;

@synthesize mAge;
@synthesize mTraitantMe;
@synthesize mNaissance;

@synthesize mFeuilleDone;
@synthesize mFeuilleGiven;
@synthesize mFeuilleNone;

@synthesize mSearchPerson;
@synthesize mSearchDiagnostic;
@synthesize mCheques;
@synthesize mEspeces;
@synthesize mAld;
@synthesize mCmu;
@synthesize mArt;
@synthesize mAt;
@synthesize mVacciner;


- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{       
    mConsultationEntity = [[[self managedObjectModel] entitiesByName] objectForKey:@"Consultation"];
    mPersonEntity = [[[self managedObjectModel] entitiesByName] objectForKey:@"Person"];
    mDiagnosticEntity = [[[self managedObjectModel] entitiesByName] objectForKey:@"Diagnostic"];
    
    mRangEntity = [[[self managedObjectModel] entitiesByName] objectForKey:@"Rang"];
    mVaccinEntity = [[[self managedObjectModel] entitiesByName] objectForKey:@"Vaccin"];
    mVaccinationEntity = [[[self managedObjectModel] entitiesByName] objectForKey:@"Vaccination"];
    
    mConsulationCtrl = [[ConsultationsController alloc] init];
    
    mImpayesCtrl = [[ImpayesController alloc] init];
    
    NSFormatter *formatter = [[MajTextFieldFormatter alloc] init];
    [mConsNom setFormatter:formatter];
    [mConsPrenom setFormatter:formatter];
    [mConsRef setFormatter:formatter];
    [mConsDiag setFormatter:formatter];
    [mConsActe setFormatter:formatter];
        
    // Insert code here to initialize your        
    [self emptyFields];
    
    [[[self mConsSomme] formatter] setFormat:@".00"];
    
    [mConsultations setDataSource:mConsulationCtrl];
    
    [mImpayes setDataSource:mImpayesCtrl];
    
    [self showDayName];
    
    [self setEnableControlsState:FALSE];
    
    [[self mConsultations] setTarget:self];
    [[self mConsultations] setDoubleAction:@selector(consultationDoubleClickAction:)];
    
    [[self mImpayes] setDoubleAction:@selector(impayesDoubleClickAction:)];
    
}

/**
    Returns the directory the application uses to store the Core Data store file. This code uses a directory named "Cabinet" in the user's Library directory.
 */
- (NSURL *)applicationFilesDirectory {

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *libraryURL = [[fileManager URLsForDirectory:NSUserDirectory inDomains:NSLocalDomainMask] lastObject];
    libraryURL = [libraryURL URLByAppendingPathComponent:@"Shared"];
    return [libraryURL URLByAppendingPathComponent:@"Cabinet"];
}

/**
    Creates if necessary and returns the managed object model for the application.
 */
- (NSManagedObjectModel *)managedObjectModel {
    if (__managedObjectModel) {
        return __managedObjectModel;
    }
	
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Cabinet" withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];    
    return __managedObjectModel;
}

/**
    Returns the persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. (The directory for the store is created, if necessary.)
 */
- (NSPersistentStoreCoordinator *) persistentStoreCoordinator {
    if (__persistentStoreCoordinator) {
        return __persistentStoreCoordinator;
    }

    NSManagedObjectModel *mom = [self managedObjectModel];
    if (!mom) {
        NSLog(@"%@:%@ No model to generate a store from", [self class], NSStringFromSelector(_cmd));
        return nil;
    }

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *applicationFilesDirectory = [self applicationFilesDirectory];
    NSError *error = nil;
    
    NSDictionary *properties = [applicationFilesDirectory resourceValuesForKeys:[NSArray arrayWithObject:NSURLIsDirectoryKey] error:&error];
        
    if (!properties) {
        BOOL ok = NO;
        if ([error code] == NSFileReadNoSuchFileError) {
            ok = [fileManager createDirectoryAtPath:[applicationFilesDirectory path] withIntermediateDirectories:YES attributes:nil error:&error];
        }
        if (!ok) {
            [[NSApplication sharedApplication] presentError:error];
            return nil;
        }
    }
    else {
        if ([[properties objectForKey:NSURLIsDirectoryKey] boolValue] != YES) {
            // Customize and localize this error.
            NSString *failureDescription = [NSString stringWithFormat:@"Expected a folder to store application data, found a file (%@).", [applicationFilesDirectory path]]; 
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setValue:failureDescription forKey:NSLocalizedDescriptionKey];
            error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:101 userInfo:dict];
            
            [[NSApplication sharedApplication] presentError:error];
            return nil;
        }
    }
    
    NSURL *url = [applicationFilesDirectory URLByAppendingPathComponent:@"Cabinet.storedata"];
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
    
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error]) {
        [[NSApplication sharedApplication] presentError:error];
        __persistentStoreCoordinator = nil;
        return nil;
    }
    
    return __persistentStoreCoordinator;
}

/**
    Returns the managed object context for the application (which is already
    bound to the persistent store coordinator for the application.) 
 */
- (NSManagedObjectContext *) managedObjectContext {
    if (__managedObjectContext) {
        return __managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setValue:@"Failed to initialize the store" forKey:NSLocalizedDescriptionKey];
        [dict setValue:@"There was an error building up the data file." forKey:NSLocalizedFailureReasonErrorKey];
        NSError *error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        [[NSApplication sharedApplication] presentError:error];
        return nil;
    }
    __managedObjectContext = [[NSManagedObjectContext alloc] init];
    [__managedObjectContext setPersistentStoreCoordinator:coordinator];

    return __managedObjectContext;
}

/**
    Returns the NSUndoManager for the application. In this case, the manager returned is that of the managed object context for the application.
 */
- (NSUndoManager *)windowWillReturnUndoManager:(NSWindow *)window {
    return [[self managedObjectContext] undoManager];
}

/**
    Performs the save action for the application, which is to send the save: message to the application's managed object context. Any encountered errors are presented to the user.
 */
- (IBAction) saveAction:(id)sender {
    NSError *error = nil;
    
    if (![[self managedObjectContext] commitEditing]) {
        NSLog(@"%@:%@ unable to commit editing before saving", [self class], NSStringFromSelector(_cmd));
    }

    if (![[self managedObjectContext] save:&error]) {
        [[NSApplication sharedApplication] presentError:error];
    }
}

- (IBAction)rechercherConsultationAction:sender
{
    NSLog(@"On Rechercher consultation");
    
    if(mEtatConsultationWnd == nil){
        mEtatConsultationWnd = [[EtatConsultationController alloc] init];
        [mEtatConsultationWnd setMManagedObjectContext:[self managedObjectContext] ];
        [mEtatConsultationWnd setMConsultationEntity:mConsultationEntity];
    }
    
    [mEtatConsultationWnd showWindow:nil];
}

- (IBAction)patientManagement:sender{

    if(mGestionPersonWnd==nil){
        mGestionPersonWnd = [[GestionPersonController alloc] init];
        [mGestionPersonWnd setMManagedObjectContext:[self managedObjectContext] ];
    }
    
    [mGestionPersonWnd showWindow:nil];
}

- (IBAction)searchPersonAction:sender{
    NSLog(@"On SearchPerson");
        
    SearchPatient *wnd = [[SearchPatient alloc] init];
        
    NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
    [request setEntity:mPersonEntity];
    
    NSSortDescriptor *nomSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Nom" ascending:YES];
    NSSortDescriptor *prenomSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Prenom" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObjects:nomSortDescriptor, prenomSortDescriptor, nil];  
    [request setSortDescriptors:sortDescriptors];  
    
    NSString * begin = [mConsNom stringValue];
    if( (begin != nil) && ([begin length]>0) )
    {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Nom BEGINSWITH[cd] %@", begin];
        [request setPredicate:predicate];
    }
    
    NSArray * result = [[self managedObjectContext] executeFetchRequest:request error:nil];
    [wnd setPersons:result];
   
    [wnd withParentWindow:window];
    
    if( [wnd returnCode] == NSOKButton )
    {
        // afficher le patient
        NSLog(@"On NSOKButton");
        
        Person* p = [wnd selectedPerson];
        [self showPerson:p];
    }
    
}

- (IBAction)searchDiagnosticAction:sender
{
    NSLog(@"On SearchDiagnostic");
    
    SearchDiagnostic *wnd = [[SearchDiagnostic alloc] init];
    [wnd setMManagedObjectContext:[self managedObjectContext]];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
    [request setEntity:mDiagnosticEntity];
    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Label" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];  
    [request setSortDescriptors:sortDescriptors];  
    
    NSString * begin = [mConsDiag stringValue];
    if( (begin != nil) && ([begin length]>0) )
    {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Label BEGINSWITH[cd] %@", begin];
        [request setPredicate:predicate];
    }
    
    NSArray * result = [[self managedObjectContext] executeFetchRequest:request error:nil];
    [wnd setDiagnostics:result];
    
    [wnd withParentWindow:window];
    
    if( [wnd returnCode] == NSOKButton )
    {
        // afficher le patient
        NSLog(@"On NSOKButton");
        
        Diagnostic *d = [wnd selectedDiagnotic];
        if(d!=nil)
            [mConsDiag setStringValue:[d Label]];
    }
    
    
}

- (NSInteger)getNbDayConsultations
{
    NSString *start = [[mConsDate dateValue] descriptionWithCalendarFormat:@"%Y-%m-%d 00:00:00 +200" timeZone:nil locale:[[NSUserDefaults standardUserDefaults]dictionaryRepresentation]];
    NSDate *startDate = [NSDate dateWithString:start];
    NSDate *endDate = [startDate dateByAddingTimeInterval:((NSTimeInterval)60*60*24)];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:mConsultationEntity];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(CreationDate >= %@) AND (CreationDate < %@)", startDate, endDate];
    [request setPredicate:predicate];
    
    [request setIncludesSubentities:NO]; //Omit subentities. Default is YES (i.e. include subentities)
    
    NSError *err;
    NSUInteger count = [[self managedObjectContext] countForFetchRequest:request error:&err];
    if(count == NSNotFound) {
        count = 0;
    }
    
    
    return count;
}

- (void) emptyFields {
    
    [[self mConsDate] setDateValue:[NSDate date]];
    [[self mConsNom] setStringValue:@""];
    [[self mConsPrenom] setStringValue:@""];
    [[self mConsDiag] setStringValue:@""];
    [[self mConsRef] setStringValue:@""];
    [[self mConsTraitement] setString:@""];
    [[self mConsInfos] setString:@""];
    [[self mConsMoyenPaiement] setStringValue:@""];
    [[self mConsActe] setStringValue:@"CTT"];
    [[self mConsSomme] setStringValue:@"23,00"];
    
    [[self mTraitantMe] setState:0];
    [[self mNaissance] setDateValue:[NSCalendarDate dateWithString:@"1870-01-01 00:00:00 +0000"]];
    [[self mAge] setStringValue:@""];
    
    [[self mFeuilleDone] setIntValue:0];
    [[self mFeuilleNone] setIntValue:0];
    [[self mFeuilleGiven] setIntValue:1];
    
    [[self mConsPaye] setState:0];

    [self showNbConsultations];
    [mConsulationCtrl emptyConsultaions];
    [[self mConsultations] reloadData];
    
    [mImpayesCtrl emptyConsultations];
    [[self mImpayes] reloadData];
    
    [[self mTotalImpayes] setStringValue:@""];
}

- (void) setEnableControlsState:(BOOL)aValue
{
    [[self mConsNom] setEnabled:aValue];
    [[self mConsPrenom] setEnabled:aValue];
    [[self mConsDiag] setEnabled:aValue];
    [[self mConsRef] setEnabled:aValue];
    
    [[self mConsTraitement] setEditable:aValue];
    [[self mConsInfos] setEditable:aValue];
    
    [[self mConsMoyenPaiement] setEnabled:aValue];
    [[self mConsActe] setEnabled:aValue];
    [[self mConsSomme] setEnabled:aValue];
    
    [[self mTraitantMe] setEnabled:aValue];
    [[self mAge] setEnabled:aValue];
    [[self mNaissance] setEnabled:aValue];
    
    [[self mFeuilleDone] setEnabled:aValue];
    [[self mFeuilleNone] setEnabled:aValue];
    [[self mFeuilleGiven] setEnabled:aValue];
    
    [[self mConsPaye] setEnabled:aValue];
    [[self mConsPaye] setEnabled:aValue];

    [[self mEnregistrer] setEnabled:aValue];
    
    [[self mNouvelActe] setEnabled:!aValue];
    
    [[self mConsultations] setEnabled:aValue];
    
    [[self mImpayes] setEnabled:aValue];
    
    [[self mSearchDiagnostic] setEnabled:aValue];
    [[self mCheques] setEnabled:aValue];
    [[self mEspeces] setEnabled:aValue];
    [[self mAld] setEnabled:aValue];
    [[self mCmu] setEnabled:aValue];
    [[self mArt] setEnabled:aValue];
    [[self mAt] setEnabled:aValue];
    [[self mVacciner] setEnabled:aValue];
    [[self mSearchPerson] setEnabled:aValue];
    [[self window] makeFirstResponder:mConsNom]; 
}

- (NSInteger)calculAge:(NSDate *)aNaissance 
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSDateComponents *dateComponentsNow = [calendar components:unitFlags fromDate:[[self mConsDate] dateValue ]];
    NSDateComponents *dateComponentsBirth = [calendar components:unitFlags fromDate:aNaissance];
    
    if (([dateComponentsNow month] < [dateComponentsBirth month]) ||
        (([dateComponentsNow month] == [dateComponentsBirth month]) && ([dateComponentsNow day] < [dateComponentsBirth day]))) {
        return [dateComponentsNow year] - [dateComponentsBirth year] - 1;
    }
    
    return [dateComponentsNow year] - [dateComponentsBirth year];
}

- (void) showPerson:(Person*)aPerson
{
    [self emptyFields];
    
    if(aPerson == nil)
        return;
    
    [[self mVacciner] setEnabled:TRUE];
    
    [[self mConsNom] setStringValue:[aPerson Nom] ];
    [[self mConsPrenom] setStringValue:[aPerson Prenom] ];
    [[self mNaissance] setDateValue:[aPerson Naissance] ];
    
    if([aPerson Commentaires] != nil)
        [[self mConsInfos] setString:[aPerson Commentaires] ];
    
    [[self mTraitantMe] setState: [[aPerson MedecinTraitant] intValue]];
    
    NSDate *minval = [NSCalendarDate dateWithString:@"1870-01-01 00:00:00 +0000"];
    if( ![[aPerson Naissance] isEqualToDate:minval] )
    {
        NSInteger age = [self calculAge:[aPerson Naissance]];
        [[self mAge] setStringValue:[NSString stringWithFormat:@"%ld an%@", age, (age>1?@"s":@"")]];
    }
    else
        [[self mAge] setStringValue:@""];
    
    [mConsulationCtrl setConsultations:[[aPerson Consultations] allObjects]];
    [[self mConsultations] reloadData];
    
    [self afficherImpayes:aPerson];
}

- (void)afficherImpayes:(Person*) aPerson{
    
    [mImpayesCtrl setConsultations:[[aPerson Consultations] allObjects]];
    [[self mImpayes] reloadData];
    
    [mImpayesCtrl getTotalImpayes];
    [[self mTotalImpayes] setStringValue:[NSString stringWithFormat:@"%1.2f €", [mImpayesCtrl getTotalImpayes]]];

}

- (IBAction)vaccinerAction:sender
{
    if(mVaccinationWnd == nil)
    {
        mVaccinationWnd = [[VaccinationController alloc] init];
        [mVaccinationWnd setMManagedObjectContext:[self managedObjectContext] ];
    
        [mVaccinationWnd setMRangEntity:mRangEntity];
        [mVaccinationWnd setMVaccinEntity:mVaccinEntity];
        [mVaccinationWnd setMVaccinationEntity:mVaccinationEntity];
    }
    
    if([[mConsDiag stringValue] length] <= 0)
        [mConsDiag setStringValue:@"Vaccin"];
    
    [mVaccinationWnd setPerson:[self getPersonForVaccination]];
    [mVaccinationWnd showWindow:nil];
}

- (IBAction)newAction:sender{
    NSLog(@"On New");
    
    if([[self mNouvelActe] isEnabled])
    {
    if(![window isVisible])
        [window makeKeyAndOrderFront:self];
    
    [self emptyFields];
    
    [self setEnableControlsState:TRUE];
    }
}

- (IBAction)okAction:sender {
    NSLog(@"On OK ");
    
    Consultation *cons = [[Consultation alloc] initWithEntity:mConsultationEntity insertIntoManagedObjectContext:[self managedObjectContext]];
    
    [self fillConsultation:cons];
    
    [[self managedObjectContext] commitEditing];
    
    
    [self emptyFields];
    
    [self setEnableControlsState:FALSE];
    
    [self saveAction:sender];
}

- (IBAction)annulerAction:sender {
    NSLog(@"On Annuler");
    [self emptyFields];
    
    [self setEnableControlsState:FALSE];
}


- (IBAction)dateAction:sender
{
    [self showDayName];
    [self showNbConsultations];
}

-(void)showNbConsultations
{
    NSInteger nbconsultations = [self getNbDayConsultations] + 1;
    [[self mConsNum] setStringValue:[NSString stringWithFormat:@"%ld", nbconsultations]];
}

- (void) showDayName
{
    NSDate* date = [[self mConsDate] dateValue];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"EEEE"];
    [[self mConsDay] setStringValue:[dateFormatter stringFromDate:date]];
       
}


- (IBAction)importerVaccinationAction:sender 
{
    [self importerAction:2];    
}

- (IBAction)importerConsultationAction:sender 
{
    [self importerAction:1];    
}

- (void)importerAction:(int)aTypeFile
{
    NSArray *fileTypes = [NSArray arrayWithObjects: @"csv", @"Export Omnis",
                          NSFileTypeForHFSTypeCode( 'TEXT' ), nil];
    
    NSOpenPanel *oPanel = [NSOpenPanel openPanel];
    [oPanel setReleasedWhenClosed:TRUE];
    
    [oPanel setAllowsMultipleSelection:YES];
    
    NSInteger result = [oPanel runModalForDirectory:NSHomeDirectory() file:nil types:fileTypes];
    if (result == NSOKButton) 
    {
        NSString *fileToOpen = [oPanel filename];
        
        Waiting *wnd = [[Waiting alloc] init];
        [wnd setUserData:fileToOpen];
        [wnd setFileType:aTypeFile];
        
        [wnd setMessage:@"Importation en cours ..."];
        
        [NSThread detachNewThreadSelector:@selector(runImport:) toTarget:self withObject:wnd];
        [wnd withParentWindow:window];
        
        [[wnd window] orderOut:nil];
    }
    
}


- (void) runImport:(Waiting*)aPanel
{
    @autoreleasepool {  
    
        NSString *fileToOpen = [aPanel UserData];
        
        NSLog(@"Importation de %@", fileToOpen);
        [self readFromPath:fileToOpen withType:[aPanel typeFile]];
        NSLog(@"Importation terminée");
        
        [aPanel performSelectorOnMainThread:@selector(end) withObject:nil waitUntilDone:YES];

    }
}

- (BOOL)readFromPath:(NSString *)absolutePath withType:(int)aTypeFile
{
    NSError *error;
    NSArray *wordListArray = [[NSArray alloc] initWithArray:[[[NSString alloc] initWithContentsOfFile:absolutePath encoding:NSNEXTSTEPStringEncoding error:&error] componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]];
    
    if ( wordListArray == nil ) 
    {
        NSLog(@"Error reading file at %@\n%@", absolutePath, [error localizedFailureReason]);
        return NO;
    }
    
    int counter = 0;
    NSString* line=nil;
    for(NSInteger i=0; i<[wordListArray count];i++)
    {
        line = [wordListArray objectAtIndex:i];
        if(line!=nil)
        {
            if(aTypeFile == 1)
            {
                if(![self importCSVConsultationLine:line])
                    NSLog(@"Failed: %@", line);
                else
                    counter++;
            }
            else if(aTypeFile == 2)
            {
                if(![self importCSVVaccinationLine:line])
                    NSLog(@"Failed: %@", line);
                else
                    counter++;
            }
        }
    }
    
    NSLog(@"%d lines imported", counter);
    
    [[self managedObjectContext] commitEditing];
    
    return YES;
}


- (BOOL) getNextValue:(NSScanner*)aScanner andCharSet:(NSCharacterSet*)aSeparator andString:(NSString**)aString
{
    BOOL res = [aScanner scanUpToCharactersFromSet:aSeparator intoString:aString];
    
    if(!res)
        *aString = @"";
    else
    {
        if ([*aString characterAtIndex:0] == '\"')
        {
            NSString *tmp;
            while ( ([*aString characterAtIndex:[*aString length]-1] != '\"') && (res) ){
                
                [aScanner scanString:@"," intoString:nil];
                res = [aScanner scanUpToCharactersFromSet:aSeparator intoString:&tmp];
                if (res) {
                    *aString = [NSString stringWithFormat:@"%@,%@", *aString, tmp];
                }
            }
            
        }
        *aString = [*aString stringByReplacingOccurrencesOfString:@"\"" withString:@""];
        res = TRUE;
    }
    
    [aScanner scanString:@"," intoString:nil];
    
    return res;
}

- (NSCalendarDate *)splitDateUp:(NSString *)aString;
{
    NSCalendarDate * aDate = [NSCalendarDate dateWithString:@"1870-01-01 00:00:00 +0000"];
	NSArray * anArray = [aString componentsSeparatedByString:@" "]; //important to put this last
	
    int date=0, month=0, year=0, hour=12, min=0;
	
    date = [[anArray objectAtIndex:0] intValue];
    if ( [anArray count] > 1 )
        month = [[anArray objectAtIndex:1] intValue];
    
    if ( [anArray count] > 2 ){
        year = [[anArray objectAtIndex:2] intValue];
        
        if(year < 100)
            year += (year>20?1900:2000);
	}
    
	if ( !month && ([anArray count] >1) ) {
        month = 1;
        NSString * monthString = @"";
        NSString * middleString = [anArray objectAtIndex:1];
        if ( [middleString length] > 2 ) monthString = [[anArray objectAtIndex:1] substringToIndex:3];
        if ( [[monthString uppercaseString] isEqualTo:@"FEV"] ) month = 2;
        if ( [[monthString uppercaseString] isEqualTo:@"MAR"] ) month = 3;
        if ( [[monthString uppercaseString] isEqualTo:@"AVR"] ) month = 4;
        if ( [[monthString uppercaseString] isEqualTo:@"MAI"] ) month = 5;
        if ( [[monthString uppercaseString] isEqualTo:@"JUN"] ) month = 6;
        if ( [[monthString uppercaseString] isEqualTo:@"JUL"] ) month = 7;
        if ( [[monthString uppercaseString] isEqualTo:@"AOU"] ) month = 8;
        if ( [[monthString uppercaseString] isEqualTo:@"SEP"] ) month = 9;
        if ( [[monthString uppercaseString] isEqualTo:@"OCT"] ) month = 10;
        if ( [[monthString uppercaseString] isEqualTo:@"NOV"] ) month = 11;
        if ( [[monthString uppercaseString] isEqualTo:@"DEC"] ) month = 12;
	}
    
    if([anArray count]==5){
        NSString* hoursStr = [anArray objectAtIndex:4];
        if([hoursStr length]>0)
        {
            NSArray* hours = [hoursStr componentsSeparatedByString:@":"];
            if([hours count]>1)
            {
                hour = [[hours objectAtIndex:0] intValue];
                min = [[hours objectAtIndex:1] intValue];
            }
        }
    }
    
	NSCalendarDate * compDate = [NSCalendarDate dateWithYear:year month:month day:date hour:hour minute:min second:0 timeZone:[NSTimeZone systemTimeZone]];
	[compDate setCalendarFormat:@"%Y-%m-%d %H:%M:%S %z"];
	if ( [aString length] ) 
        aDate = [NSCalendarDate dateWithString:[compDate description]];
	return aDate;
}

- (BOOL) importCSVConsultationLine:(NSString*)aLine
{
    NSScanner *scanner = [NSScanner scannerWithString:aLine];
    
    NSCharacterSet *semicolonSet = [NSCharacterSet characterSetWithCharactersInString:@","];
    
    NSString *tmp;
    
    NSDate* date;
    NSString *nom;
    NSString *prenom;
    NSNumber* payee;
    NSDecimalNumber *prix;
    NSString *acte;
    NSNumber* donnee;
    NSString *payement;
    NSString *reference;
    NSString *patho;
    NSString *trait;
    NSString *comments;
    
    // date
    if(![self getNextValue:scanner andCharSet:semicolonSet andString:&tmp])
        return FALSE;
    
    date=[self splitDateUp:tmp];
    if(date == nil)
        return FALSE;
    
    //date = [NSDate date];
    // nom
    if(![self getNextValue:scanner andCharSet:semicolonSet andString:&nom])
        return FALSE;
    
    // prenom
    if(![self getNextValue:scanner andCharSet:semicolonSet andString:&prenom])
        return FALSE;
    
    if( ([nom length]<=0) || ([prenom length]<=0) )
        return FALSE;
    
    // feuille donnee
    [self getNextValue:scanner andCharSet:semicolonSet andString:&tmp];
    if ( [tmp caseInsensitiveCompare:@"oui"] == NSOrderedSame ){
        donnee = [NSNumber numberWithInteger:FeuilleDonnee];
    }else if( [tmp caseInsensitiveCompare:@"non"] == NSOrderedSame ){
        donnee = [NSNumber numberWithInteger:FeuilleGardee];
    }else{
        donnee = [NSNumber numberWithInteger:FeuilleNonFaite];
    }
    
    if([self getNextValue:scanner andCharSet:semicolonSet andString:&tmp])
        prix = [NSDecimalNumber decimalNumberWithString:tmp locale:[[NSUserDefaults standardUserDefaults]dictionaryRepresentation]];
    
    [self getNextValue:scanner andCharSet:semicolonSet andString:&acte];
    
    // consultation payee
    [self getNextValue:scanner andCharSet:semicolonSet andString:&tmp];
    payee = [NSNumber numberWithInteger:( [tmp caseInsensitiveCompare:@"oui"] == NSOrderedSame ? 1 : 0 )];
    
    [self getNextValue:scanner andCharSet:semicolonSet andString:&tmp];
    [self getNextValue:scanner andCharSet:semicolonSet andString:&tmp];
    
    // text libre
    [self getNextValue:scanner andCharSet:semicolonSet andString:&comments];
    
    // moyen de payement
    [self getNextValue:scanner andCharSet:semicolonSet andString:&tmp];
    payement = [self GetMoyenPayement:tmp];
    
    [self getNextValue:scanner andCharSet:semicolonSet andString:&tmp];
    [self getNextValue:scanner andCharSet:semicolonSet andString:&tmp];
    
    [self getNextValue:scanner andCharSet:semicolonSet andString:&reference];
    
    [self getNextValue:scanner andCharSet:semicolonSet andString:&patho];
    
    [self getNextValue:scanner andCharSet:semicolonSet andString:&trait];
    
    Consultation *cons = [[Consultation alloc] initWithEntity:mConsultationEntity insertIntoManagedObjectContext:[self managedObjectContext]];
    [self fillConsultation:cons at:date firstame:prenom lastame:nom diag:patho ref:reference obs:@"" payement:payement acte:acte donnee:donnee payee:payee traitement:trait prix:prix medecin:0 naissance:[NSCalendarDate dateWithString:@"1870-01-01 00:00:00 +0000"] comments:comments];
    
    return TRUE;   
}

- (NSString*)GetMoyenPayement:(NSString*) aMode
{
    if( aMode == nil )
        return @"";
    
    if ( [[aMode uppercaseString] isEqualTo:@"C"] || [[aMode uppercaseString] isEqualTo:@"P"] ||
         [[aMode uppercaseString] isEqualTo:@"CCP"] || [[aMode uppercaseString] isEqualTo:@"P"])
        return @"Cheque";
    
    if ( [[aMode uppercaseString] isEqualTo:@"E"] )
        return @"Especes";
    
    return aMode;
}


- (BOOL) importCSVVaccinationLine:(NSString*)aLine
{    
    NSScanner *scanner = [NSScanner scannerWithString:aLine];          
    NSCharacterSet *semicolonSet = [NSCharacterSet characterSetWithCharactersInString:@","];
    
    NSDate *minval = [NSCalendarDate dateWithString:@"1870-01-01 00:00:00 +0000"];
    
    NSString *tmp;
    
    NSDate* dateVaccination = minval;
    NSDate* dateNaissance = minval;
    NSDate* dateRappel = minval;
    NSString *nom;
    NSString *prenom;
    NSNumber* sex;    
    NSString *nomVaccin;
    NSString *lot;
    NSString *rang;
    NSNumber* type;
    
    // nom personne
    if(![self getNextValue:scanner andCharSet:semicolonSet andString:&nom])
        return FALSE;
    
    // sex
    [self getNextValue:scanner andCharSet:semicolonSet andString:&tmp];
    if([tmp caseInsensitiveCompare:@"1"] == NSOrderedSame)
    {
        sex = [NSNumber numberWithInt:Madame];
    }
    else if([tmp caseInsensitiveCompare:@"2"] == NSOrderedSame)
    {
        sex = [NSNumber numberWithInt:Mademoiselle];
    }
    else if([tmp caseInsensitiveCompare:@"3"] == NSOrderedSame)
    {
        sex = [NSNumber numberWithInt:Monsieur];
    }
    else
    {
        sex = [NSNumber numberWithInt:Enfant];
    }
    
    if(![self getNextValue:scanner andCharSet:semicolonSet andString:&prenom])
        return FALSE;
   
    if([self getNextValue:scanner andCharSet:semicolonSet andString:&tmp])
        dateNaissance = [self splitDateUp:tmp];
    
    // jour naissance pas pris
    [self getNextValue:scanner andCharSet:semicolonSet andString:&tmp];
    
    if([self getNextValue:scanner andCharSet:semicolonSet andString:&tmp])
        dateVaccination = [self splitDateUp:tmp];    
    
    if(![self getNextValue:scanner andCharSet:semicolonSet andString:&nomVaccin])
        return FALSE;
    
    if(![self getNextValue:scanner andCharSet:semicolonSet andString:&lot])
        return FALSE;
    
    // code pas pris
    [self getNextValue:scanner andCharSet:semicolonSet andString:&tmp];
    
    // age pas pris
    [self getNextValue:scanner andCharSet:semicolonSet andString:&tmp];
    
    // jour naissance pas pris
    [self getNextValue:scanner andCharSet:semicolonSet andString:&tmp];
    [self getNextValue:scanner andCharSet:semicolonSet andString:&tmp];
    [self getNextValue:scanner andCharSet:semicolonSet andString:&tmp];
    
    if([self getNextValue:scanner andCharSet:semicolonSet andString:&tmp])
        dateRappel = [self splitDateUp:tmp];    
    
    [self getNextValue:scanner andCharSet:semicolonSet andString:&rang];
    
    [self getNextValue:scanner andCharSet:semicolonSet andString:&tmp];
    
    NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
    [f setNumberStyle:NSNumberFormatterDecimalStyle];
    type = [f numberFromString:tmp];

    Vaccination *vaccination = [[Vaccination alloc] initWithEntity:mVaccinationEntity insertIntoManagedObjectContext:[self managedObjectContext]];
    [vaccination setRang:rang];
    [vaccination setDate:dateVaccination];
    [vaccination setRappel:dateRappel];
    [vaccination setLot:lot];
    
    [self addRang:rang];
    Vaccin* vac = [self getVaccin:nomVaccin withCode:type];
    if(vac == nil)
    {
        vac = [[Vaccin alloc] initWithEntity:mVaccinEntity insertIntoManagedObjectContext:[self managedObjectContext]];
        [vac setNom:nomVaccin];
        [vac setType:type];
        
        [vaccination setVaccin:vac];
         
    }
    else
        [vaccination setVaccin:vac];
    
    Person *p = [self getPerson:nom andPrenom:prenom];
    if(p == nil)
    {
        p = [[Person alloc] initWithEntity:mPersonEntity insertIntoManagedObjectContext:[self managedObjectContext]];
        [p setNom:nom];
        [p setPrenom:prenom];
        [p setNaissance:dateNaissance];
        [p setSexe:sex];
        
        [vaccination setPerson:p];
        
    }
    else
    {
        if( [[p Naissance] isEqualToDate:minval] )
            [p setNaissance:dateNaissance];
        
        [p setSexe:sex];
        
        [vaccination setPerson:p];
    }
    
    
    return TRUE;    
}

- (BOOL)addExists:(NSString*)aNom andPrenom:(NSString*)aPrenom
{
    if( ([aNom length]<=0) || ([aPrenom length]<=0) )
        return FALSE;
    
    if([self personExists:aNom andPrenom:aPrenom])
        return FALSE;
    
    Person *p = [[Person alloc] initWithEntity:mPersonEntity insertIntoManagedObjectContext:[self managedObjectContext]];
    
    [p setNom:aNom ];
    [p setPrenom:aPrenom ];
    
    
    return TRUE;
}

- (BOOL)personExists:(NSString*)aNom andPrenom:(NSString*)aPrenom
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
    [request setEntity:mPersonEntity];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(Nom = %@) AND (Prenom = %@)", aNom, aPrenom];
    [request setPredicate:predicate];
    
    [request setIncludesSubentities:NO]; //Omit subentities. Default is YES (i.e. include subentities)
    
    NSError *err;
    NSUInteger count = [[self managedObjectContext] countForFetchRequest:request error:&err];
    if(count == NSNotFound) {
        count = 0;
    }
    
    
    return count>0;
}

- (Person*)getPersonForVaccination
{
    Person *p = [self getPerson:[self formatInput:mConsNom] andPrenom:[self formatInput:mConsPrenom]];      
    if(p==nil)
    {
        p = [[Person alloc] initWithEntity:mPersonEntity insertIntoManagedObjectContext:[self managedObjectContext]];
        [p setNom:[self formatInput:mConsNom]];
        [p setPrenom:[self formatInput:mConsPrenom]];
        
        [p setMedecinTraitant:[NSNumber numberWithInteger:[[self mTraitantMe] state]]];
        [p setNaissance:[[self mNaissance] dateValue]];
        [p setCommentaires:[self formatTVInput:mConsInfos] ];
    }
    
    return p;
}

- (Person*)getPerson:(NSString*)aNom andPrenom:(NSString*)aPrenom
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
    [request setEntity:mPersonEntity];
        
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(Nom = %@) AND (Prenom = %@)", aNom, aPrenom];
    [request setPredicate:predicate];
    
    NSArray * result = [[self managedObjectContext] executeFetchRequest:request error:nil];
    
    if([result count]<=0)
        return nil;
    
    return [result objectAtIndex:0];
}

- (void) addRang:(NSString*)aRang
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
    [request setEntity:mRangEntity];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(Label = %@)", aRang];
    [request setPredicate:predicate];
    
    NSArray * result = [[self managedObjectContext] executeFetchRequest:request error:nil];
    
    if([result count]>0)
        return;
        
    Rang *r = [[Rang alloc] initWithEntity:mRangEntity insertIntoManagedObjectContext:[self managedObjectContext]];
    
    [r setLabel:aRang ];    
}

- (Vaccin*) getVaccin:(NSString*)aNomVaccin withCode:(NSNumber*)aCode
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
    [request setEntity:mVaccinEntity];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(Nom = %@)", aNomVaccin];
    [request setPredicate:predicate];
    
    NSArray * result = [[self managedObjectContext] executeFetchRequest:request error:nil];
    
    if([result count]<=0)
        return nil;
    
    return [result objectAtIndex:0];
}


- (void)showMessage:(NSString*)aMessage{
    NSAlert *alert = [[NSAlert alloc] init];
    [alert setMessageText:aMessage];
    [alert runModal];
    
    // s'abonner à l'évènement on close pour détruire le fenêtre
}

- (void) tableViewSelectionDidChange:(NSNotification *)aNotification
{    
    Consultation *cons = [mConsulationCtrl getConsultationAtIndex:[mConsultations selectedRow]];
    
    // activer ou désactiver le bouton de recopie du traitement;
    [mRenouvellement setEnabled:(cons != nil)];

}

- (NSString *)tableView:(NSTableView *)aTableView toolTipForCell:(NSCell *)aCell 
                   rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)row mouseLocation:(NSPoint)mouseLocation
{
    Consultation *c = [mConsulationCtrl getConsultationAtIndex:row]; 
    if(c == nil)
        return @"";
    
    if( [[c Traitement] length] <= 0 )
        return @"--";
    
    return [c Traitement];
}

- (NSString*) formatInput:(NSTextField*)aTextField {
    if( aTextField == nil )
        return @"";
    
    if( [aTextField stringValue] == nil )
        return @"";
    
    return [NSString stringWithFormat:@"%@", [aTextField stringValue]];
}

- (NSString*) formatTVInput:(NSTextView*)aTextView {
    if( aTextView == nil )
        return @"";
    
    if( [aTextView string] == nil )
        return @"";
    
    return [NSString stringWithFormat:@"%@", [aTextView string]];
}

- (IBAction)renouvellementAction:sender
{
    NSInteger idx = [[self mConsultations] selectedRow];
    Consultation *cons = [mConsulationCtrl getConsultationAtIndex:idx];
    
    if(cons == nil)
        return;
    
    [[self mConsRef]setStringValue:[cons Reference]];
    [[self mConsDiag]setStringValue:[cons Diagnostic]];
    [[self mConsTraitement]setString:[cons Traitement]];
}

- (NSInteger)getFeuille
{
    if([mFeuilleDone intValue] == 1 )
        return FeuilleGardee;
    
    if([mFeuilleGiven intValue] == 1 )
        return FeuilleDonnee;
    
    return FeuilleNonFaite;
}


- (void) fillConsultation:
    (Consultation*)aConsultation at:(NSDate*)aDate 
    firstame:(NSString*)aFirstame lastame:(NSString*)aLastname
    diag:(NSString*)aDiag ref:(NSString*)aRef obs:(NSString*)aObs
    payement:(NSString*)aPayement acte:(NSString*)aActe
    donnee:(NSNumber*)aDonnee payee:(NSNumber*)aPayee
    traitement:(NSString*)aTrait prix:(NSDecimalNumber*)aPrix
    medecin:(NSInteger) aTraitant naissance:(NSDate*) aNaissance comments:(NSString*)aComments
{
    
    NSString* nom = aLastname;
    NSString* prenom = aFirstame;
    
    Person *p = [self getPerson:nom andPrenom:prenom];
    if(p == nil)
    {
        p = [[Person alloc] initWithEntity:mPersonEntity insertIntoManagedObjectContext:[self managedObjectContext]];
        [p setNom:nom];
        [p setPrenom:prenom];
        [p setMedecinTraitant:[NSNumber numberWithInteger:aTraitant]];
        [p setNaissance:aNaissance];
        
        [aConsultation setPerson:p];
        
    }
    else
        [aConsultation setPerson:p];
    
    [self addDiagnostic:aDiag];
    [aConsultation setCreationDate:aDate];
    [aConsultation setDiagnostic:aDiag];
    [aConsultation setReference:aRef];
    [aConsultation setObservations:aObs];
    [aConsultation setPayement:aPayement];
    [aConsultation setActe:aActe];
    [aConsultation setEtatFeuille:aDonnee];
    [aConsultation setPaye:aPayee];
    [aConsultation setTraitement:aTrait];
    [aConsultation setSomme:aPrix];
    [aConsultation setObservations:aComments];
}


- (void) fillConsultation:(Consultation*)aConsultation{
    
    NSString* nom = [self formatInput:mConsNom];
    NSString* prenom = [self formatInput:mConsPrenom];
    
    Person *p = [self getPerson:nom andPrenom:prenom];
    if(p == nil)
    {
        p = [[Person alloc] initWithEntity:mPersonEntity insertIntoManagedObjectContext:[self managedObjectContext]];
        [p setNom:nom];
        [p setPrenom:prenom];

        [aConsultation setPerson:p];
    }
    else
        [aConsultation setPerson:p];
    
    [[aConsultation Person] setMedecinTraitant:[NSNumber numberWithInteger:[[self mTraitantMe] state]]];
    [[aConsultation Person] setNaissance:[[self mNaissance] dateValue]];
    [[aConsultation Person] setCommentaires:[self formatTVInput:mConsInfos] ];
    
    [aConsultation setCreationDate:[[self mConsDate] dateValue]];
    [aConsultation setDiagnostic:[self formatInput:mConsDiag] ];
    [self addDiagnostic:[self formatInput:mConsDiag]];
    [aConsultation setReference:[self formatInput:mConsRef] ];
    [aConsultation setPayement:[self formatInput:mConsMoyenPaiement] ];
    [aConsultation setActe:[self formatInput:mConsActe] ];
    [aConsultation setEtatFeuille:[NSNumber numberWithInteger:[self getFeuille]]];
    [aConsultation setPaye:[NSNumber numberWithInteger:[[self mConsPaye] state]]];
    
    [aConsultation setTraitement:[self formatTVInput:mConsTraitement] ];
    
    NSString *somme = [self formatInput:mConsSomme];
    if( [somme length] <= 0 )
        somme = [somme stringByAppendingFormat:@"0"];
    
    NSDecimalNumber *decimal = [NSDecimalNumber decimalNumberWithString:somme locale:[[NSUserDefaults standardUserDefaults]dictionaryRepresentation]];
    [aConsultation setSomme:decimal ];
}

- (void) addDiagnostic:(NSString*)aDiagnostic
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
    [request setEntity:mDiagnosticEntity];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(Label = %@)", aDiagnostic];
    [request setPredicate:predicate];
    
    NSArray * result = [[self managedObjectContext] executeFetchRequest:request error:nil];
    
    if([result count]>0)
        return;
    
    Diagnostic *diag = [[Diagnostic alloc] initWithEntity:mDiagnosticEntity insertIntoManagedObjectContext:[self managedObjectContext]];
    [diag setLabel:aDiagnostic];
    
}

- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {

    // Save changes in the application's managed object context before the application terminates.

    if (!__managedObjectContext) {
        return NSTerminateNow;
    }

    if (![[self managedObjectContext] commitEditing]) {
        NSLog(@"%@:%@ unable to commit editing to terminate", [self class], NSStringFromSelector(_cmd));
        return NSTerminateCancel;
    }

    if (![[self managedObjectContext] hasChanges]) {
        return NSTerminateNow;
    }

    NSError *error = nil;
    if (![[self managedObjectContext] save:&error]) {

        // Customize this code block to include application-specific recovery steps.              
        BOOL result = [sender presentError:error];
        if (result) {
            return NSTerminateCancel;
        }

        NSString *question = NSLocalizedString(@"Could not save changes while quitting. Quit anyway?", @"Quit without saves error question message");
        NSString *info = NSLocalizedString(@"Quitting now will lose any changes you have made since the last successful save", @"Quit without saves error question info");
        NSString *quitButton = NSLocalizedString(@"Quit anyway", @"Quit anyway button title");
        NSString *cancelButton = NSLocalizedString(@"Cancel", @"Cancel button title");
        NSAlert *alert = [[NSAlert alloc] init];
        [alert setMessageText:question];
        [alert setInformativeText:info];
        [alert addButtonWithTitle:quitButton];
        [alert addButtonWithTitle:cancelButton];

        NSInteger answer = [alert runModal];
        alert = nil;
        
        if (answer == NSAlertAlternateReturn) {
            return NSTerminateCancel;
        }
    }

    return NSTerminateNow;
}


- (IBAction)chequeAction:sender
{
    [mConsMoyenPaiement setStringValue:@"Cheque"];
    [[self mConsPaye] setState:1];
}

- (IBAction)especesAction:sender
{
    [mConsMoyenPaiement setStringValue:@"Especes"];
    [[self mConsPaye] setState:1];
}

- (IBAction)aldAction:sender
{
    [mConsMoyenPaiement setStringValue:@"ALD"];
    [[self mConsPaye] setState:0];
}

- (IBAction)cmuAction:sender
{
    [mConsMoyenPaiement setStringValue:@"CMU"];
    [[self mConsPaye] setState:0];
}

- (IBAction)atAction:sender
{
    [mConsMoyenPaiement setStringValue:@"AT"];
    [[self mConsPaye] setState:0];
}

- (IBAction)artAction:sender
{
    [mConsMoyenPaiement setStringValue:@"Art 115"];
    [[self mConsPaye] setState:0];
}

- (BOOL)textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector {
    
    if (commandSelector == @selector(insertTab:)) {
        [[textView window] selectNextKeyView:[textView nextResponder]];
        return YES;
    }
    else if (commandSelector == @selector(insertBacktab:)) {
        [[textView window] selectPreviousKeyView:[textView nextResponder]];
        return YES;
    }
    
    return NO;
}


- (IBAction)consultationDoubleClickAction:(id)sender
{
    NSTableView *tbview = (NSTableView*)sender;
     
    Consultation *c = [mConsulationCtrl getConsultationAtIndex:[tbview selectedRow]]; 
    if(c == nil)
        return;

    [self renouvellementAction:sender];
}

-(IBAction)impayesDoubleClickAction:(id)sender{
    
    NSTableView *tbview = (NSTableView*)sender;
    
    Consultation *selectedCons = [mImpayesCtrl getConsultationAtIndex:[tbview selectedRow]];
    if(selectedCons == nil)
        return;
    
    if(mConsultationWnd == nil)
    {
        mConsultationWnd = [[ConsultationViewController alloc] init];
        [mConsultationWnd setIEnregistrerNotifiable:self];
    }
    [mConsultationWnd setConsultation:selectedCons];
    [mConsultationWnd showWindow:nil];
}

-(void) Enregistre{
    
    NSString* nom = [self formatInput:mConsNom];
    NSString* prenom = [self formatInput:mConsPrenom];
    
    Person *p = [self getPerson:nom andPrenom:prenom];
    if(p == nil)
        return;
    
    [self afficherImpayes:p];
}

- (void)textDidChange:(NSNotification *)aNotification
{
    
    NSTextView *textView = [aNotification object];
    if(textView == nil)
        return;
    
    NSString * value = [textView string];
    if((value == nil)|| ([value length]<=0))
        return;
    
    NSRange range = [textView selectedRange];
    
    [textView setString:[value uppercaseString]];
    [textView setSelectedRange:range];
    
}

@end
